{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Part 4, Topic 1: Power and Hamming Weight Relationship"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "NOTE: This lab references some (commercial) training material on [ChipWhisperer.io](https://www.ChipWhisperer.io). You can freely execute and use the lab per the open-source license (including using it in your own courses if you distribute similarly), but you must maintain notice about this source location. Consider joining our training course to enjoy the full experience.\n",
    "\n",
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**SUMMARY:** *In the previous part of SCA101, we used the fact a relationship exists between the value of the bits being manipulated on a microcontroller to recover an AES key*\n",
    "\n",
    "*In this lab, we'll improve our model by looking at how power relates to hamming weight.*\n",
    "\n",
    "**LEARNING OUTCOMES:**\n",
    "\n",
    "* Understand hamming weight\n",
    "* Calculate hamming weight of a byte\n",
    "* Identify the point where the SBox output is being written\n",
    "* Plot power consumption at the SBox output vs. hamming weight\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## AES Model"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We'll be looking at the SBox again, so grab your implementation from the last section:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# ###################\n",
    "# Add your code here\n",
    "# ###################\n",
    "raise NotImplementedError(\"Add your code here, and delete this.\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#Simple test vectors - if you get the check-mark printed all OK.\n",
    "assert(aes_internal(0xAB, 0xEF) == 0x1B)\n",
    "assert(aes_internal(0x22, 0x01) == 0x26)\n",
    "print(\"✔️ OK to continue!\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Hamming Weight"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Recall that the reason that there's a relationship between power consumption and the microcontroller's internal data is that setting this data takes power. We've also seen that the more data that is set, the greater the average power draw. It's not far fetched, then, that there should be some sort of consistant relationship between the number of bits set to 1, called the **Hamming weight** and the power consumed by doing so.\n",
    "\n",
    "Hamming weight, despite being a pretty simple idea, actually isn't trivial to calculate (see https://en.wikipedia.org/wiki/Hamming_weight#Efficient_implementation). You can write a function to do this, but in Python it's far easier to just convert to a string of bits and count the `\"1\"`s:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def calc_hamming_weight(n):\n",
    "    return bin(n).count(\"1\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Even better, create a lookup table (aka do the calculation for each number between 0 and 255 and stick them in an array):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# ###################\n",
    "# Add your code here\n",
    "# ###################\n",
    "raise NotImplementedError(\"Add Your Code Here\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "assert HW[0x53] == 4\n",
    "print(\"✔️ OK to continue!\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Our first issue that we run into is that we don't know where the SBox operation is happening. It should be happening pretty close to the beginning (let's guess and say within the first 2000 samples). One thought is that we could group the traces by hamming weight and assign a colour to each one. If we plot that, we might be able to find a pattern:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from bokeh.plotting import figure, show\n",
    "from bokeh.io import output_notebook\n",
    "from bokeh.palettes import brewer\n",
    "\n",
    "output_notebook()\n",
    "p = figure()\n",
    "\n",
    "plot_start = 0\n",
    "plot_end = 2000\n",
    "xrange = list(range(len(trace_array[0]))[plot_start:plot_end])\n",
    "bnum = 0\n",
    "color_mapper = brewer['PRGn'][9]\n",
    "\n",
    "for tnum in range(len(trace_array)):\n",
    "    hw_of_byte = HW[aes_internal(textin_array[tnum][bnum], key[bnum])]\n",
    "    p.line(xrange, trace_array[tnum][plot_start:plot_end], line_color=color_mapper[hw_of_byte])\n",
    "\n",
    "show(p)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Unfortunately, you'll probably find that this plot doesn't really tell us much; the part of power consumption associated with the SBox output is just too small to pick out. We could try averaging the hamming weight groups to make things more distinct, but that doesn't solve the fundamental issue of the SBox output being lost in the noise of everything else happening on the chip.\n",
    "\n",
    "Instead, let's approach this from a different angle. Really, what we want here is to remove the overall \"shape\" of the trace and just leave the signal from the SBox output. We could just pick a trace and subtract it from each group, but subtracting an average of all the traces instead will make the plot more distinct. Even better would be to have an even weighting between all of the hamming weight groups, since the extreme hamming weights (0 and 8) are far less common than the middle values, but this won't end up being super necessary (though you can still attempt this if you'd like).  The plot will also be more distinct (and plot a lot faster) if we average all the hamming weight groups to remove any outliers as well. Try implementing this (we'll again handle the plotting for you):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# ###################\n",
    "# Add your code here\n",
    "# ###################\n",
    "raise NotImplementedError(\"Add Your Code Here\")\n",
    "\n",
    "xrange = range(len(trace_array[0]))[plot_start:plot_end]\n",
    "color_mapper = brewer['PRGn'][9]\n",
    "for hw in range(9):  \n",
    "    p.line(xrange, (hw_averages[hw]-avg_trace)[plot_start:plot_end], line_color=color_mapper[hw])\n",
    "    \n",
    "show(p)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Plotting this, you should get a very distinct spot where the colours separate. This is where the SBox operation is occuring. In fact, it's probably distinct enough that you can choose the SBox loction solely by where the graph is largest:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sbox_loc = np.argmax(abs(hw_averages[0]-avg_trace))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now that we know where the SBox operation is happening, plot the hamming weight averages by their hamming weight at `sboc_loc`.\n",
    "\n",
    "**HINT: You may want to convert your hw_averages to a numpy array to allow you to access by column. `hw_averages[:,sbox_loc]` will give you `hw_averages` at the sbox_loc.**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# ###################\n",
    "# Add your code here\n",
    "# ###################\n",
    "raise NotImplementedError(\"Add Your Code Here\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You should find that the relationship is mostly linear, which probably won't come out of left field. It makes sense that setting 8 data bits will take roughly 8x the power that setting one does. \n",
    "\n",
    "You will likely also find that the slope of the relationship is negative, unless you're on the ChipWhisperer Nano. This happens for a good reason. If you remember how we are measuring the current into the device, you'll find out that the voltage will go DOWN for an INCREASE in current. You can see this in the following figure:\n",
    "\n",
    "```     \n",
    "        Rshunt\n",
    "(Vin)----v^v^v^----------||------(To ChipWhisperer)\n",
    "                |\n",
    "                |\n",
    "       (To microcontroller)\n",
    "```\n",
    "\n",
    "For the ChipWhisperer Nano, the slope is positive due to the presence of an inverting amplifier on the input of the measurement port.\n",
    "\n",
    "We are measuring the drop across the shunt resistor. An increase in the current causes a higher voltage across the resistor. When no current flows there is no drop across the resistor. But since we only measure a single end of the resistor, we see a higher voltage when no current flows.\n",
    "\n",
    "We can fix the slope by simply inverting the measurement direction (adding a - in front of the measurement).\n",
    "\n",
    "Now that we know where the SBox operation is happening, try going back to the original plot and zoom in to that section. Can you pick out the difference between the hamming weights now?"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Conclusions & Next Steps\n",
    "\n",
    "With this lab, you should be reasonably convinced that there is a linear relationship between the hamming weight of data being set in a microcontroller and the power it consumes from doing so.\n",
    "\n",
    "In the next lab, we'll see how this can be used to greatly improve over our DPA attack."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "<small>NO-FUN DISCLAIMER: This material is Copyright (C) NewAE Technology Inc., 2015-2020. ChipWhisperer is a trademark of NewAE Technology Inc., claimed in all jurisdictions, and registered in at least the United States of America, European Union, and Peoples Republic of China.\n",
    "\n",
    "Tutorials derived from our open-source work must be released under the associated open-source license, and notice of the source must be *clearly displayed*. Only original copyright holders may license or authorize other distribution - while NewAE Technology Inc. holds the copyright for many tutorials, the github repository includes community contributions which we cannot license under special terms and **must** be maintained as an open-source release. Please contact us for special permissions (where possible).\n",
    "\n",
    "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.</small>"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
